--select dbo.fn_Format('ABC%sEFG%s', 'XXX,')

if exists(select * from sysobjects where id = object_id('dbo.fn_Format') and xtype in ('if', 'tf', 'fn'))
drop function dbo.fn_Format
GO

create function dbo.fn_Format(
  @Format				varchar(2000),
  @Values			  varchar(2000),
  @Separation		char(1)
)
RETURNS VARCHAR(4000)
AS
BEGIN
declare  @ReValue					varchar(4000)
declare  @ReplaceValue			varchar(500)
declare  @tmpValues				varchar(2000)

set @ReValue = @Format
set @tmpValues = @Values

while CharIndex('%s', @ReValue) > 0 
begin
  if Len(@tmpValues) > 0
  begin
    if CharIndex(@Separation, @tmpValues) > 0
    begin
      set  @ReplaceValue = substring(@tmpValues, 1, CharIndex(@Separation, @tmpValues) - 1)
      set  @tmpValues = substring(@tmpValues, CharIndex(@Separation, @tmpValues) + 1, Len(@tmpValues))
    end else begin
      set  @ReplaceValue = substring(@tmpValues, 1, Len(@tmpValues))
      set  @tmpValues = ''
    end
  end else
    set @ReplaceValue = ''
  set  @ReValue = Stuff(@ReValue, CharIndex('%s', @ReValue), 2, @ReplaceValue)
end

Return IsNull(@ReValue, '')
END